package com.jinzhi.jzweb.controller.api;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.jinzhi.common.constants.ConstMessages;
import com.jinzhi.common.constants.MessagesEnum;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.ShiroUtils;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.DateUtil;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 合同相关接口
 * @author mengzhichao
 * @create 2023-04-27-13:54
 */
@RestController
@RequestMapping("/jzApi/JazSysContract")
public class ApiJazSysContractController {


    @Autowired
    private JazSysContractService jazSysContractService; //合同表


    @Autowired
    private JazUserOrderService jazUserOrderService; //订单表

    @Autowired
    private UserService userService; //用户表

    @Autowired
    private JazUserCommentService jazUserCommentService; //用户评价表

    int contractConclude = 2000; //签合同所需积分

    @Autowired
    private JazInformService jazInformService; //用户评价表

    @Autowired
    private JazUserIntegralService jazUserIntegralService; //积分明细表

    @Autowired
    private WxValidationService wxValidationService; //校验敏感词

    @Autowired
    private JazUserAuntService jazUserAuntService; //月嫂表

    @Autowired
    private JazUserDemandService jazUserDemandService; //用户需求表

    @Autowired
    private JazMessageService jazMessageService;

    @Autowired
    private JazSysContractTemplateService jazSysContractTemplateService;

    @Autowired
    private JazSysProjectService jazSysProjectService; //服务表

    @Autowired
    private JazUserCommentClassifyService jazUserCommentClassifyService; //服务表

    @Autowired
    private JazUserCommentDescriptionService jazUserCommentDescriptionService; //服务表

    @Autowired
    private JazGroupOrderService jazGroupOrderService; //团购订单表

    @Autowired
    private JazProdTypeService jazProdTypeService;

    /**
     * 查询指定类型合同
     */
    @GetMapping("/selProjectContract")
    public Result<?> selProjectContract(String projectId){
        Wrapper<JazSysContractTemplateDO> wrapper = new EntityWrapper<JazSysContractTemplateDO>();
        wrapper.eq("project_id",projectId);
        wrapper.eq("status",0); //正常状态
        JazSysContractTemplateDO jazSysContractTemplateDO = jazSysContractTemplateService.selectOne(wrapper);
        return Result.ok(jazSysContractTemplateDO);
    }







    /**
     * 发起签约扣积分接口
     */
    @GetMapping("/initiateSign")
    public Result<?> initiateSign(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());//合同发起人

        if (Double.valueOf(userDO.getCurrentPoints()) < contractConclude){
            return Result.ok(1); //积分不足签订失败
        }
        return Result.ok(0);
    }





    /**
     * 查询该用户是否签约
     * auntId：月嫂id
     * @return
     */
    @GetMapping("/isContract")
    public Result<?> isContract(Long auntUserId){
        EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
        wrapper.eq("signing_id",auntUserId);//订单签约人月嫂
        wrapper.isNotNull("status");//状态不为空的
        wrapper.andNew().ne("status",2);//不等于已完成
        wrapper.andNew().ne("status",3);//不等于已取消
        wrapper.andNew().ne("status",4);//不等于已转让
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectOne(wrapper);
        if (jazUserOrderDO != null){
            jazUserOrderDO.setIs(1); //已签约
            return Result.ok(jazUserOrderDO);
        }else {
            jazUserOrderDO =new JazUserOrderDO();
            jazUserOrderDO.setIs(0); //未签约
            return Result.ok(jazUserOrderDO);
        }
    }




    /**
     * 合同发起
     * @param projectId
     * @param auntUserId
     * @param startTime
     * @param endTime
     * @param totalPrice
     * @param address
     * @return
     */
    @PostMapping ("/projectContractConclude")
    @Transactional
    public Result<?> projectContractConclude(String projectId,String auntUserId, Date startTime,Date endTime,String totalPrice,String address,String signatureJia,String identityCardJia,String phoneJia,String homeAddressJia,String nameJia){
        Wrapper<JazSysContractTemplateDO> wrapper = new EntityWrapper<JazSysContractTemplateDO>();
        wrapper.eq("project_id",projectId); //正常状态
        wrapper.eq("status",0); //正常状态
        JazSysContractTemplateDO jazSysContractDO = jazSysContractTemplateService.selectOne(wrapper); //查询出合同
        if (jazSysContractDO ==null){
            return Result.fail("请先配置合同");
        }

        UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());//合同发起人
        JazUserOrderDO jazUserOrderDO =new JazUserOrderDO();
        jazUserOrderDO.setInitiateId(userDO.getId()); //合同发起人
        jazUserOrderDO.setSigningId(Long.valueOf(auntUserId)); //签订人
        jazUserOrderDO.setContractId(jazSysContractDO.getId()); //合同id
        jazUserOrderDO.setTotalPrice(new BigDecimal(totalPrice)); //订单总价
        jazUserOrderDO.setConcludeStatus(1); //合同默认待签署状态
        jazUserOrderDO.setAddress(address); //服务地址
        jazUserOrderDO.setProjectId(projectId); //服务类型
        jazUserOrderDO.setOrderType(2);//订单类型 需求订单
        jazUserOrderDO.setNumber(generateOrderNumber(20));
        jazUserOrderDO.setNameJia(nameJia); //甲方姓名
        jazUserOrderDO.setSignatureJia(signatureJia); //发起人（甲方）签名
        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(startTime, Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(endTime, Locale.CHINA) + " 23:59:59");
        jazUserOrderDO.setStartTime(start); //服务开始时间
        jazUserOrderDO.setEndTime(end); //服务结束时间
        jazUserOrderDO.setCreateTime(new Date()); //订单生成时间
        jazUserOrderDO.setIdentityCardJia(identityCardJia); //身份证号码
        jazUserOrderDO.setPhoneJia(phoneJia); //手机号
        jazUserOrderDO.setHomeAddressJia(homeAddressJia); //家庭住址

        JazMessageDO jazMessageDO = new JazMessageDO();
        jazMessageDO.setMessageType(1);
        jazMessageDO.setSenderId(getUser.getId());
        jazMessageDO.setReceiverId(Long.valueOf(auntUserId));
        jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_109.getMsg());
        jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_109.getNum());
        jazMessageDO.setHasSendSms(true);
        jazMessageDO.setIsRead(0);
        jazMessageService.senMessage(jazMessageDO);

//
//        //当前积分 - 扣除积分
//        userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) - contractConclude));
//        userService.updateById(userDO);
//
//        JazUserIntegralDO userIntegralDO = new JazUserIntegralDO();
//        userIntegralDO.setIntegralDetail("-2000"); //积分
//        userIntegralDO.setSysUserid(userDO.getId()); //用户id
//        userIntegralDO.setIntegralTime(new Date()); //时间
//        userIntegralDO.setIntegralWay("积分冻结"); //用途
//        userIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
//        jazUserIntegralService.insert(userIntegralDO);

        jazUserOrderService.insert(jazUserOrderDO);
        return Result.ok();
    }














    /**
     * 合同发起
     * @param projectId
     * @param auntUserId
     * @param startTime
     * @param endTime
     * @param totalPrice
     * @param address
     * @return
     */
    @PostMapping ("/projectContractConclude2")
    @Transactional
    public Result<?> projectContractConclude2(String projectId,String auntUserId, Date startTime,Date endTime,String totalPrice,String address,String signatureJia,String identityCardJia,String phoneJia,String homeAddressJia,String nameJia,String signatureYi,String identityCardYi,String phoneYi,String homeAddressYi,String nameYi,String xqId){
        Wrapper<JazSysContractTemplateDO> wrapper = new EntityWrapper<JazSysContractTemplateDO>();
        wrapper.eq("project_id",projectId); //正常状态
        wrapper.eq("status",0); //正常状态
        JazSysContractTemplateDO jazSysContractDO = jazSysContractTemplateService.selectOne(wrapper); //查询出合同
        if (jazSysContractDO ==null){
            return Result.fail("请先配置合同");
        }

        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());//合同发起人
        JazUserOrderDO jazUserOrderDO =new JazUserOrderDO();
        jazUserOrderDO.setInitiateId(userDO.getId()); //合同发起人
        jazUserOrderDO.setSigningId(Long.valueOf(auntUserId)); //签订人
        jazUserOrderDO.setContractId(jazSysContractDO.getId()); //合同id
        jazUserOrderDO.setTotalPrice(new BigDecimal(totalPrice)); //订单总价
        jazUserOrderDO.setConcludeStatus(1); //合同默认待签署状态
        jazUserOrderDO.setAddress(address); //服务地址
        jazUserOrderDO.setProjectId(projectId); //服务类型
        jazUserOrderDO.setSignSource("1"); //签约来源
        jazUserOrderDO.setDemandId(xqId); //需求id
        if (StringUtil.isNotNull(jazUserOrderDO.getNameJia())) {
            jazUserOrderDO.setNameJia(nameJia); //甲方姓名
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getSignatureJia())) {
            jazUserOrderDO.setSignatureJia(signatureJia); //发起人（甲方）签名
        }
        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(startTime, Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(endTime, Locale.CHINA) + " 23:59:59");
        jazUserOrderDO.setStartTime(start); //服务开始时间
        jazUserOrderDO.setEndTime(end); //服务结束时间
        jazUserOrderDO.setCreateTime(new Date()); //订单生成时间
        if (StringUtil.isNotNull(jazUserOrderDO.getIdentityCardJia())) {
            jazUserOrderDO.setIdentityCardJia(identityCardJia); //身份证号码
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getPhoneJia())) {
            jazUserOrderDO.setPhoneJia(phoneJia); //手机号
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getHomeAddressJia())) {
            jazUserOrderDO.setHomeAddressJia(homeAddressJia); //家庭住址
        }
        if (StringUtil.isNotNull(signatureYi)){
            jazUserOrderDO.setSignatureYi(signatureYi); //签约人（乙方）签名
        }
        if (StringUtil.isNotNull(nameYi)){
            jazUserOrderDO.setNameYi(nameYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(identityCardYi)){
            jazUserOrderDO.setIdentityCardYi(identityCardYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(phoneYi)){
            jazUserOrderDO.setPhoneYi(phoneYi); //乙方手机号
        }
        if (StringUtil.isNotNull(homeAddressYi)){
            jazUserOrderDO.setHomeAddressYi(homeAddressYi); //乙方家庭住址
        }

//        //当前积分 - 扣除积分
//        userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) - contractConclude));
//        userService.updateById(userDO);
//
//        JazUserIntegralDO userIntegralDO = new JazUserIntegralDO();
//        userIntegralDO.setIntegralDetail("-2000"); //积分
//        userIntegralDO.setSysUserid(userDO.getId()); //用户id
//        userIntegralDO.setIntegralTime(new Date()); //时间
//        userIntegralDO.setIntegralWay("积分冻结"); //用途
//        userIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
//        jazUserIntegralService.insert(userIntegralDO);

        jazUserOrderService.insert(jazUserOrderDO);
        return Result.ok();
    }











    public static String generateOrderNumber(int length) {
        // 检查长度是否合法
        if (length <= 0) {
            throw new IllegalArgumentException("订单编号长度必须大于0");
        }

        // 计算随机部分的长度
        int randomPartLength = length - 14; // 时间戳部分长度为14

        // 如果随机部分长度小于等于0，则直接使用时间戳作为订单编号
        if (randomPartLength <= 0) {
            return generateTimestamp();
        }

        // 生成随机部分
        String randomPart = generateRandomDigits(randomPartLength);

        // 组合时间戳部分和随机部分，形成订单编号
        String orderNumber = generateTimestamp() + randomPart;

        return orderNumber;
    }

    // 生成时间戳部分
    private static String generateTimestamp() {
        LocalDateTime now = LocalDateTime.now();
        return now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    }


    // 生成指定长度的随机数字字符串
    private static String generateRandomDigits(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            builder.append(random.nextInt(10)); // 生成0到9之间的随机数字
        }
        return builder.toString();
    }



    /**
     * 合同取消
     */
    @PostMapping ("/cancelProjectContract")
    @Transactional
    public Result<?> cancelProjectContract(String orderId){
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(orderId);
        jazUserOrderDO.setConcludeStatus(3);
        jazUserOrderService.updateById(jazUserOrderDO);
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());//合同发起人
        //当前积分 + 扣除积分
//        userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) + contractConclude));
//        userService.updateById(userDO);
//
//
//        JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
//        jazUserIntegralDO.setIntegralDetail("+"+contractConclude); //积分
//        jazUserIntegralDO.setSysUserid(userDO.getId()); //用户id
//        jazUserIntegralDO.setIntegralTime(new Date()); //时间
//        jazUserIntegralDO.setIntegralWay("冻结积分退回"); //用途
//        jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
//        jazUserIntegralService.insert(jazUserIntegralDO);

        return Result.ok();
    }








    /**
     * 查询订单评价内容
     */
    @GetMapping ("/selOrderComment")
    public Result<List> selOrderComment(String type){
        EntityWrapper entityWrapper =new EntityWrapper();
        entityWrapper.eq("comment_type",type);
        JazUserCommentClassifyDO jazUserCommentClassifyDO = jazUserCommentClassifyService.selectOne(entityWrapper);
        if(jazUserCommentClassifyDO!= null){
            entityWrapper =new EntityWrapper();
            entityWrapper.eq("comment_classify_id",jazUserCommentClassifyDO.getId());
            List list = jazUserCommentDescriptionService.selectList(entityWrapper);
            return Result.ok(list);
        }
        return Result.ok();
    }













    /**
     * 订单评价
     * 订单编号，服务评价，内容，图片
     */
    @PostMapping ("/orderComment")
    @Transactional
    public Result<Map> orderComment(String orderId,String commentDescriptionIds,String grade){
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(orderId);

        JazUserCommentDO jazUserCommentDO =new JazUserCommentDO();
        jazUserCommentDO.setCommentOrderId(Long.valueOf(orderId)); //订单id
        jazUserCommentDO.setCommentUserid(jazUserOrderDO.getInitiateId()); //评论人id
        jazUserCommentDO.setGrade(grade); //星级

        Long signingId = jazUserOrderDO.getSigningId();
        EntityWrapper entityWrapper =new EntityWrapper();
        entityWrapper.eq("sys_userid",signingId);
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(entityWrapper);
        jazUserCommentDO.setCommentdObjectid(jazUserAuntDO.getId()); //被评论人月嫂id

        jazUserCommentDO.setCommentTime(new Date()); //评论时间
        jazUserCommentDO.setCommentDescriptionId(commentDescriptionIds); //评论描述id，分割
        jazUserCommentDO.setType(2);
        jazUserCommentService.insert(jazUserCommentDO);


        if (jazUserOrderDO.getOrderType() == 1) { //如果是团购订单
            EntityWrapper wrapper =new EntityWrapper();
            wrapper.eq("order_no",jazUserOrderDO.getNumber());
            JazGroupOrderDO jazGroupOrderDO = jazGroupOrderService.selectOne(wrapper); //根据订单编号查询出团购订单信息
            JazUserCommentDO jazUserCommentDO2 = new JazUserCommentDO();
            jazUserCommentDO2.setCommentOrderId(jazGroupOrderDO.getGroupProdId()); //团购商品id
            jazUserCommentDO2.setCommentUserid(jazUserOrderDO.getInitiateId()); //评论人id
            jazUserCommentDO2.setGrade(grade); //星级
            jazUserCommentDO2.setCommentdObjectid(jazGroupOrderDO.getGroupProdId()); //被评论人也是商品id
            jazUserCommentDO2.setCommentTime(new Date()); //评论时间
            jazUserCommentDO2.setCommentDescriptionId(commentDescriptionIds); //评论描述id，分割
            jazUserCommentDO2.setType(3);
            jazUserCommentService.insert(jazUserCommentDO2);
        }


        return Result.ok();
    }






    /**
     * 我的合同列表查询
     *
     * 1.我发起的，2.待签署，3.已签署，4.已经取消 5.已终止
     */
    @GetMapping("/selUserContract")
    public Result<?> selUserContract(String type){
        UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
        EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
        wrapper.isNotNull("initiate_id"); //发起人不为空
        wrapper.isNotNull("signing_id"); //签约人不为空
        wrapper.isNotNull("contract_id");//合同不为空
//        wrapper.isNotNull("identity_card_jia");//甲方身份证号码不为空

        if (type.equals("1")){ //查询我发起的
            wrapper.eq("initiate_id",userDO.getId());
            wrapper.eq("conclude_status",1);
        }else if (type.equals("2")){ //查询待签署的
            wrapper.eq("signing_id",userDO.getId());
            wrapper.eq("conclude_status",1);
        }else if (type.equals("3")){ //查询已签署的
            wrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
            wrapper.andNew().eq("conclude_status",2);
        }else if (type.equals("4")){ //查询已取消的
            wrapper.eq("initiate_id",userDO.getId());
            wrapper.eq("conclude_status",3);
        }else if (type.equals("5")){ //查询已终止
            wrapper.eq("initiate_id",userDO.getId());
            wrapper.eq("conclude_status",4);
        }
        wrapper.orderBy("create_time",false);
        List<JazUserOrderDO> jazUserOrderDOS = jazUserOrderService.selectList(wrapper);
        for (int i=0;i<jazUserOrderDOS.size();i++){
            JazSysContractTemplateDO jazSysContractTemplateDO = jazSysContractTemplateService.selectById(jazUserOrderDOS.get(i).getContractId());
            if(jazSysContractTemplateDO!=null) {
                jazUserOrderDOS.get(i).setContractName(jazSysContractTemplateDO.getName());
            }else {
                jazUserOrderDOS.get(i).setContractName("保洁合同");
            }
        }

        EntityWrapper<JazUserOrderDO> countWrapper = new EntityWrapper<JazUserOrderDO>();
        countWrapper.eq("signing_id",userDO.getId());
        countWrapper.eq("conclude_status",1);
        int count = jazUserOrderService.selectCount(countWrapper); //待签署的数量

        Map map =new HashMap();
        map.put("count",count);
        map.put("userOrder",jazUserOrderDOS);
        return Result.ok(map);
    }



    /**
     * 我的合同列表查询
     *
     * 2.待签署，3.已签署，4.已经取消 5.已终止
     */
    @GetMapping("/selUserContract2")
    public Result<?> selUserContract2(String type){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());
        EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
        wrapper.isNotNull("initiate_id"); //发起人不为空
        wrapper.isNotNull("signing_id"); //签约人不为空
        wrapper.isNotNull("contract_id");//合同不为空

        if (type.equals("2")){ //查询待签署的
            wrapper.eq("signing_id",userDO.getId());
            wrapper.eq("conclude_status",1);
        }else if (type.equals("3")){ //查询已签署的
            wrapper.eq("signing_id",userDO.getId());
            wrapper.andNew().eq("conclude_status",2);
        }else if (type.equals("4")){ //查询已取消的
            wrapper.eq("signing_id",userDO.getId());
            wrapper.eq("conclude_status",3);
        }else if (type.equals("5")){ //查询已终止
            wrapper.eq("signing_id",userDO.getId());
            wrapper.eq("conclude_status",4);
        }
        wrapper.orderBy("create_time",false);
        List<JazUserOrderDO> jazUserOrderDOS = jazUserOrderService.selectList(wrapper);
        for (int i=0;i<jazUserOrderDOS.size();i++){
            JazSysContractTemplateDO jazSysContractTemplateDO = jazSysContractTemplateService.selectById(jazUserOrderDOS.get(i).getContractId());
            if(jazSysContractTemplateDO!=null) {
                jazUserOrderDOS.get(i).setContractName(jazSysContractTemplateDO.getName());
            }else {
                jazUserOrderDOS.get(i).setContractName("保洁合同");
            }
        }

        EntityWrapper<JazUserOrderDO> countWrapper = new EntityWrapper<JazUserOrderDO>();
        countWrapper.eq("signing_id",userDO.getId());
        countWrapper.eq("conclude_status",1);
        int count = jazUserOrderService.selectCount(countWrapper); //待签署的数量

        Map map =new HashMap();
        map.put("count",count);
        map.put("userOrder",jazUserOrderDOS);
        return Result.ok(map);
    }










    /**
     * 查询我的订单列表
     * 0 待开始  1进行中 2已完成 3已取消 4已转让
     *
     */
    @GetMapping("/selUserOrder")
    public Result<?> selUserOrder(String type){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());

        String role = "1"; //默认为月嫂
        EntityWrapper<JazUserAuntDO> userWrapper = new EntityWrapper<JazUserAuntDO>();
        userWrapper.eq("sys_userid",userDO.getId());
        userWrapper.eq("audit_result","0");
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(userWrapper);
        if (jazUserAuntDO == null){    //如果 == null表示没有认证月嫂
            role = "0";
        }
        EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
        //查询待开始订单数量
        wrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
        wrapper.andNew().eq("status",type);
        List<JazUserOrderDO> jazUserOrderDOS = jazUserOrderService.selectList(wrapper);

        for (int i=0;i<jazUserOrderDOS.size();i++){
            JazSysContractTemplateDO jazSysContractDO = jazSysContractTemplateService.selectById(jazUserOrderDOS.get(i).getContractId());
            jazUserOrderDOS.get(i).setRole(role);
            if (jazSysContractDO!=null) {
                jazUserOrderDOS.get(i).setContractName(jazSysContractDO.getName());
            }else {
                Long jazProdTypeId = jazUserOrderDOS.get(i).getJazProdTypeId();
                JazProdTypeDO jazProdTypeDO = jazProdTypeService.selectById(jazProdTypeId);
                jazUserOrderDOS.get(i).setContractName(jazProdTypeDO.getName());
            }
            EntityWrapper commentWrapper =new EntityWrapper();
            commentWrapper.eq("comment_userid",userDO.getId());
            commentWrapper.eq("comment_order_id",jazUserOrderDOS.get(i).getId());
            List list = jazUserCommentService.selectList(commentWrapper);
            if (list.size()>0){
                jazUserOrderDOS.get(i).setIsComment(1); //已评价
            }else {
                jazUserOrderDOS.get(i).setIsComment(0); //未评价
            }
            if (jazUserOrderDOS.get(i).getOrderType() ==1){ //团购
                Date startTime = jazUserOrderDOS.get(i).getStartTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                String formattedDate = sdf.format(startTime);
                System.out.println("Formatted Date: " + formattedDate);
                try {
                    // 转换回 Date 类型
                    Date parsedDate = sdf.parse(formattedDate);
                    System.out.println("Parsed Date: " + parsedDate);
                    jazUserOrderDOS.get(i).setStartTime(parsedDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else {
                Date startTime = jazUserOrderDOS.get(i).getStartTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

                String formattedDate = sdf.format(startTime);
                System.out.println("Formatted Date: " + formattedDate);
                try {
                    // 转换回 Date 类型
                    Date parsedDate = sdf.parse(formattedDate);
                    System.out.println("Parsed Date: " + parsedDate);
                    jazUserOrderDOS.get(i).setStartTime(parsedDate);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }

        return Result.ok(jazUserOrderDOS);
    }








    /**
     * 修改订单状态
     * 0 待开始  1进行中 2已完成 3已取消
     */
    @PostMapping("/updateUserOrderStatus")
    @Transactional
    public Result<?> updateUserOrderStatus(String orderId,int status){
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(orderId);
        jazUserOrderDO.setStatus(status);


        if (status == 3 || status == 2){ //如果取消订单 或者结束订单
            EntityWrapper<JazUserAuntDO> fqrwrapper = new EntityWrapper<JazUserAuntDO>();
            fqrwrapper.eq("sys_userid",jazUserOrderDO.getInitiateId()); //订单发起人
            fqrwrapper.eq("audit_result","0");
            JazUserAuntDO fqrjazUserAuntDO = jazUserAuntService.selectOne(fqrwrapper);
            if (fqrjazUserAuntDO != null){ //如果 != null表示认证月嫂
                fqrjazUserAuntDO.setSigningStatus(0); //月嫂状态改为待签约
                jazUserAuntService.updateById(fqrjazUserAuntDO);
            }

            EntityWrapper<JazUserAuntDO> qyrwrapper = new EntityWrapper<JazUserAuntDO>();
            qyrwrapper.eq("sys_userid",jazUserOrderDO.getSigningId()); //订单签约人
            qyrwrapper.eq("audit_result","0");
            JazUserAuntDO qyrjazUserAuntDO = jazUserAuntService.selectOne(qyrwrapper);
            if (qyrjazUserAuntDO != null){ //如果 != null表示认证月嫂
                qyrjazUserAuntDO.setSigningStatus(0); //月嫂状态改为待签约
                jazUserAuntService.updateById(qyrjazUserAuntDO);
            }
        }
        if (status == 2){ //结束订单
            Long initiateId = jazUserOrderDO.getInitiateId();//订单发起人id
            Long signingId = jazUserOrderDO.getSigningId();//订单签约人id

            UserDO fqruserDO = userService.selectById(initiateId);
            UserDO qyruserDO = userService.selectById(signingId);

            EntityWrapper<JazUserAuntDO> fqrwrapper = new EntityWrapper<JazUserAuntDO>();
            fqrwrapper.eq("sys_userid",fqruserDO.getId()); //订单发起人
            fqrwrapper.eq("audit_result","0");
            JazUserAuntDO fqrjazUserAuntDO = jazUserAuntService.selectOne(fqrwrapper);
            if (fqrjazUserAuntDO != null){ //如果 != null表示认证月嫂
                fqrjazUserAuntDO.setOrderCount(fqrjazUserAuntDO.getOrderCount() + 1); //提前结束订单数+1
                jazUserAuntService.updateById(fqrjazUserAuntDO);
            }

            EntityWrapper<JazUserAuntDO> qyrwrapper = new EntityWrapper<JazUserAuntDO>();
            qyrwrapper.eq("sys_userid",qyruserDO.getId()); //订单签约人
            qyrwrapper.eq("audit_result","0");
            JazUserAuntDO qyrjazUserAuntDO = jazUserAuntService.selectOne(qyrwrapper);
            if (qyrjazUserAuntDO != null){ //如果 != null表示认证月嫂
                qyrjazUserAuntDO.setOrderCount(qyrjazUserAuntDO.getOrderCount() + 1); //提前结束订单数+1
                jazUserAuntService.updateById(qyrjazUserAuntDO);
            }


//            fqruserDO.setCurrentPoints(String.valueOf(Double.valueOf(fqruserDO.getCurrentPoints()) + 200));
//            fqruserDO.setAccumulatedPoints(String.valueOf(Double.valueOf(fqruserDO.getAccumulatedPoints()) +200));
//
//            qyruserDO.setCurrentPoints(String.valueOf(Double.valueOf(qyruserDO.getCurrentPoints()) + 200));
//            qyruserDO.setAccumulatedPoints(String.valueOf(Double.valueOf(qyruserDO.getAccumulatedPoints()) +200));
//
//            userService.updateById(fqruserDO);
//            userService.updateById(qyruserDO);
//
//
//            JazUserIntegralDO fqrUserIntegralDO = new JazUserIntegralDO();
//            fqrUserIntegralDO.setIntegralDetail("+"+200); //积分
//            fqrUserIntegralDO.setSysUserid(fqruserDO.getId()); //用户id
//            fqrUserIntegralDO.setIntegralTime(new Date()); //时间
//            fqrUserIntegralDO.setIntegralWay("完成订单"); //用途
//            fqrUserIntegralDO.setCurrentIntegral(fqruserDO.getCurrentPoints()); //当前积分
//            jazUserIntegralService.insert(fqrUserIntegralDO);
//
//
//            JazUserIntegralDO qyrUserIntegralDO = new JazUserIntegralDO();
//            qyrUserIntegralDO.setIntegralDetail("+"+200); //积分
//            qyrUserIntegralDO.setSysUserid(qyruserDO.getId()); //用户id
//            qyrUserIntegralDO.setIntegralTime(new Date()); //时间
//            qyrUserIntegralDO.setIntegralWay("完成订单"); //用途
//            qyrUserIntegralDO.setCurrentIntegral(qyruserDO.getCurrentPoints()); //当前积分
//            jazUserIntegralService.insert(qyrUserIntegralDO);

        }

        jazUserOrderService.updateById(jazUserOrderDO);
        return Result.ok();
    }









    /**
     * 合同详情查询
     */
    @GetMapping("/selUserContractDetails")
    public Result<?> selUserContractDetails(String id){
        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(id);
        if(jazUserOrderDO.getOrderType() != 1) { //不是团购再去查合同
            JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserOrderDO.getProjectId());
            jazUserOrderDO.setProjectName(String.valueOf(jazSysProjectDO.getName()));
            //查询乙方身份证号码
            UserDO userDO = userService.selectById(jazUserOrderDO.getSigningId());
            if(userDO!=null && userDO.getIdNumber()!=null){
                jazUserOrderDO.setIdentityCardYi(userDO.getIdNumber());
            }
        }else {
            Long jazProdTypeId = jazUserOrderDO.getJazProdTypeId();
            JazProdTypeDO jazProdTypeDO = jazProdTypeService.selectById(jazProdTypeId);
            jazUserOrderDO.setProjectName(jazProdTypeDO.getName());
        }
        return Result.ok(jazUserOrderDO);
    }








    /**
     * 合同修改——签署
     */
    @PostMapping("/updateUserContract")
    @Transactional
    public Result<?> updateUserContract(String id,Date startTime,Date endTime,String totalPrice,String address,String identityCardJia,String phoneJia,String homeAddressJia,String nameJia){

        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(id);
        if (startTime != null){
            Date start = DateUtil.strToDateLong(DateUtil.dateToStr(startTime, Locale.CHINA) + " 00:00:00");
            jazUserOrderDO.setStartTime(start); //服务开始时间
        }
        if (endTime != null){
            Date end = DateUtil.strToDateLong(DateUtil.dateToStr(endTime, Locale.CHINA) + " 23:59:59");
            jazUserOrderDO.setEndTime(end); //服务结束时间
        }
        if (nameJia != null){
            jazUserOrderDO.setNameJia(nameJia); //服务地址
        }
        if (StringUtil.isNotNull(address)){
            jazUserOrderDO.setAddress(address); //服务地址
        }
        if (StringUtil.isNotNull(identityCardJia)){
            jazUserOrderDO.setIdentityCardJia(identityCardJia); //甲方身份证号码
        }
        if (StringUtil.isNotNull(phoneJia)){
            jazUserOrderDO.setPhoneJia(phoneJia); //甲方电话
        }
        if (StringUtil.isNotNull(homeAddressJia)){
            jazUserOrderDO.setHomeAddressJia(homeAddressJia); //家庭地址
        }
        if (StringUtil.isNotNull(totalPrice)){
            jazUserOrderDO.setTotalPrice(new BigDecimal(totalPrice)); //订单总价
        }
        jazUserOrderDO.setUpdateTime(new Date()); //订单修改时间
        jazUserOrderService.updateById(jazUserOrderDO);
        return Result.ok();
    }












    /**
     * 合同修改——签署
     */
    @PostMapping("/updateUserContract2")
    @Transactional
    public Result<?> updateUserContract2(String id,Date startTime,Date endTime,String totalPrice,String address,String identityCardJia,String phonejia,String homeAddressJia,String nameJia,String signatureYi,String identityCardYi,String phoneYi,String homeAddressYi,String nameYi){

        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(id);
        if (startTime != null){
            Date start = DateUtil.strToDateLong(DateUtil.dateToStr(startTime, Locale.CHINA) + " 00:00:00");
            jazUserOrderDO.setStartTime(start); //服务开始时间
        }
        if (endTime != null){
            Date end = DateUtil.strToDateLong(DateUtil.dateToStr(endTime, Locale.CHINA) + " 23:59:59");
            jazUserOrderDO.setEndTime(end); //服务结束时间
        }
        if (nameJia != null){
            jazUserOrderDO.setNameJia(nameJia); //服务地址
        }
        if (StringUtil.isNotNull(address)){
            jazUserOrderDO.setAddress(address); //服务地址
        }
        if (StringUtil.isNotNull(identityCardJia)){
            jazUserOrderDO.setIdentityCardJia(identityCardJia); //甲方身份证号码
        }
        if (StringUtil.isNotNull(phonejia)){
            jazUserOrderDO.setPhoneJia(phonejia); //甲方电话
        }
        if (StringUtil.isNotNull(homeAddressJia)){
            jazUserOrderDO.setHomeAddressJia(homeAddressJia); //家庭地址
        }
        if (StringUtil.isNotNull(totalPrice)){
            jazUserOrderDO.setTotalPrice(new BigDecimal(totalPrice)); //订单总价
        }

        if (StringUtil.isNotNull(signatureYi)){
            jazUserOrderDO.setSignatureYi(signatureYi); //签约人（乙方）签名
        }
        if (StringUtil.isNotNull(nameYi)){
            jazUserOrderDO.setNameYi(nameYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(identityCardYi)){
            jazUserOrderDO.setIdentityCardYi(identityCardYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(phoneYi)){
            jazUserOrderDO.setPhoneYi(phoneYi); //乙方手机号
        }
        if (StringUtil.isNotNull(homeAddressYi)){
            jazUserOrderDO.setHomeAddressYi(homeAddressYi); //乙方家庭住址
        }

        jazUserOrderDO.setUpdateTime(new Date()); //订单修改时间
        jazUserOrderService.updateById(jazUserOrderDO);
        return Result.ok();
    }










    /**
     * 用户签署接口
     */
    @PostMapping("/userContractSign")
    @Transactional
    public Result<?> userContractSign(String id,String signatureYi,String identityCardYi,String phoneYi,String homeAddressYi,String nameYi){

        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(id);

        if (StringUtil.isNotNull(signatureYi)){
            jazUserOrderDO.setSignatureYi(signatureYi); //签约人（乙方）签名
        }
        if (StringUtil.isNotNull(nameYi)){
            jazUserOrderDO.setNameYi(nameYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(identityCardYi)){
            jazUserOrderDO.setIdentityCardYi(identityCardYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(phoneYi)){
            jazUserOrderDO.setPhoneYi(phoneYi); //乙方手机号
        }
        if (StringUtil.isNotNull(homeAddressYi)){
            jazUserOrderDO.setHomeAddressYi(homeAddressYi); //乙方家庭住址
        }
        jazUserOrderDO.setStatus(0); //订单状态待开始
        jazUserOrderDO.setConcludeStatus(2); //合同已经签署
        jazUserOrderDO.setUpdateTime(new Date()); //订单修改时间
        jazUserOrderService.updateById(jazUserOrderDO);


        //添加新闻通知
        UserDO fqrUserDO = userService.selectById(jazUserOrderDO.getInitiateId()); //订单发起人
        JazInformDO jazInformDO = new JazInformDO();
        String userName = "";
        if (fqrUserDO.getNickname() != null&&!fqrUserDO.getNickname().equals("")){
            userName = fqrUserDO.getNickname();
        }else {
            userName = fqrUserDO.getMobile();
        }
        jazInformDO.setContent("恭喜用户：" + userName + "签约成功！");
        jazInformDO.setUserId(fqrUserDO.getId()); //创建人id
        jazInformDO.setCreateTime(new Date()); //创建时间
        jazInformService.insert(jazInformDO);





        EntityWrapper<JazUserAuntDO> qdrwrapper = new EntityWrapper<JazUserAuntDO>();
        qdrwrapper.eq("sys_userid",jazUserOrderDO.getSigningId());  //签订人
        qdrwrapper.eq("audit_result","0");
        JazUserAuntDO qdrjazUserAuntDO = jazUserAuntService.selectOne(qdrwrapper);
        if (qdrjazUserAuntDO != null){
            qdrjazUserAuntDO.setSigningStatus(1);
            jazUserAuntService.updateById(qdrjazUserAuntDO);
        }
        EntityWrapper<JazUserAuntDO> fqrwrapper = new EntityWrapper<JazUserAuntDO>();
        fqrwrapper.eq("sys_userid",jazUserOrderDO.getInitiateId());  //发起人
        fqrwrapper.eq("audit_result","0");
        JazUserAuntDO fqrjazUserAuntDO = jazUserAuntService.selectOne(fqrwrapper);
        if (fqrjazUserAuntDO != null){
            fqrjazUserAuntDO.setSigningStatus(1);
            jazUserAuntService.updateById(fqrjazUserAuntDO);
        }


        /** 发送消息 */
        //发给用户
        JazMessageDO jazMessageDO = new JazMessageDO();
        jazMessageDO.setMessageType(1);
        jazMessageDO.setSenderId(jazUserOrderDO.getSigningId());
        jazMessageDO.setReceiverId(jazUserOrderDO.getInitiateId());
        jazMessageDO.setMessageContent(MessagesEnum.MESSAGE_110.getMsg());
        jazMessageDO.setMessageNum(MessagesEnum.MESSAGE_110.getNum());
        jazMessageDO.setHasSendSms(true);
        jazMessageDO.setUserOrderId(jazUserOrderDO.getId());
        jazMessageService.senMessage(jazMessageDO);
        //发给阿姨
        JazMessageDO jazMessageDO2 = new JazMessageDO();
        jazMessageDO2.setMessageType(1);
        jazMessageDO2.setSenderId(jazUserOrderDO.getInitiateId());
        jazMessageDO2.setReceiverId(jazUserOrderDO.getSigningId());
        jazMessageDO2.setMessageContent(MessagesEnum.MESSAGE_111.getMsg());
        jazMessageDO2.setMessageNum(MessagesEnum.MESSAGE_111.getNum());
        jazMessageDO2.setHasSendSms(true);
        jazMessageDO2.setUserOrderId(jazUserOrderDO.getId());
        jazMessageService.senMessage(jazMessageDO2);

        return Result.ok();
    }










    /**
     * 用户签署接口
     */
    @PostMapping("/userContractSign2")
    @Transactional
    public Result<?> userContractSign2(String id,Date startTime,Date endTime,String totalPrice,String address,String signatureJia,String identityCardJia,String phonejia,String homeAddressJia,String nameJia,String signatureYi,String identityCardYi,String phoneYi,String homeAddressYi,String nameYi,String xqId){

        JazUserOrderDO jazUserOrderDO = jazUserOrderService.selectById(id);

        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(startTime, Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(endTime, Locale.CHINA) + " 23:59:59");
        jazUserOrderDO.setStartTime(start); //服务开始时间
        jazUserOrderDO.setEndTime(end); //服务结束时间
        jazUserOrderDO.setTotalPrice(new BigDecimal(totalPrice)); //订单总价
        jazUserOrderDO.setAddress(address); //服务地址

        if (StringUtil.isNotNull(jazUserOrderDO.getNameJia())) {
            jazUserOrderDO.setNameJia(nameJia); //甲方姓名
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getSignatureJia())) {
            jazUserOrderDO.setSignatureJia(signatureJia); //发起人（甲方）签名
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getIdentityCardJia())) {
            jazUserOrderDO.setIdentityCardJia(identityCardJia); //身份证号码
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getPhoneJia())) {
            jazUserOrderDO.setPhoneJia(phonejia); //手机号
        }
        if (StringUtil.isNotNull(jazUserOrderDO.getHomeAddressJia())) {
            jazUserOrderDO.setHomeAddressJia(homeAddressJia); //家庭住址
        }


        if (StringUtil.isNotNull(signatureYi)){
            jazUserOrderDO.setSignatureYi(signatureYi); //签约人（乙方）签名
        }
        if (StringUtil.isNotNull(nameYi)){
            jazUserOrderDO.setNameYi(nameYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(identityCardYi)){
            jazUserOrderDO.setIdentityCardYi(identityCardYi); //乙方身份证号码
        }
        if (StringUtil.isNotNull(phoneYi)){
            jazUserOrderDO.setPhoneYi(phoneYi); //乙方手机号
        }
        if (StringUtil.isNotNull(homeAddressYi)){
            jazUserOrderDO.setHomeAddressYi(homeAddressYi); //乙方家庭住址
        }
        jazUserOrderDO.setStatus(0); //订单状态待开始
        jazUserOrderDO.setConcludeStatus(2); //合同已经签署
        jazUserOrderDO.setUpdateTime(new Date()); //订单修改时间
        jazUserOrderService.updateById(jazUserOrderDO);


        JazUserDemandDO jazUserDemandDO = jazUserDemandService.selectById(xqId);
        jazUserDemandDO.setIsSign(1);//状态改为已签约就不在展示了
        jazUserDemandService.updateById(jazUserDemandDO);


        //添加新闻通知
        UserDO fqrUserDO = userService.selectById(jazUserOrderDO.getInitiateId()); //订单发起人
        JazInformDO jazInformDO = new JazInformDO();
        String userName = "";
        if (fqrUserDO.getNickname() != null&&!fqrUserDO.getNickname().equals("")){
            userName = fqrUserDO.getNickname();
        }else {
            userName = fqrUserDO.getMobile();
        }
        jazInformDO.setContent("恭喜用户：" + userName + "签约成功！");
        jazInformDO.setUserId(fqrUserDO.getId()); //创建人id
        jazInformDO.setCreateTime(new Date()); //创建时间
        jazInformService.insert(jazInformDO);





        EntityWrapper<JazUserAuntDO> qdrwrapper = new EntityWrapper<JazUserAuntDO>();
        qdrwrapper.eq("sys_userid",jazUserOrderDO.getSigningId());  //签订人
        qdrwrapper.eq("audit_result","0");
        JazUserAuntDO qdrjazUserAuntDO = jazUserAuntService.selectOne(qdrwrapper);
        if (qdrjazUserAuntDO != null){
            qdrjazUserAuntDO.setSigningStatus(1);
            jazUserAuntService.updateById(qdrjazUserAuntDO);
        }
        EntityWrapper<JazUserAuntDO> fqrwrapper = new EntityWrapper<JazUserAuntDO>();
        fqrwrapper.eq("sys_userid",jazUserOrderDO.getInitiateId());  //发起人
        fqrwrapper.eq("audit_result","0");
        JazUserAuntDO fqrjazUserAuntDO = jazUserAuntService.selectOne(fqrwrapper);
        if (fqrjazUserAuntDO != null){
            fqrjazUserAuntDO.setSigningStatus(1);
            jazUserAuntService.updateById(fqrjazUserAuntDO);
        }
        return Result.ok();
    }











    /**
     * 获取用户订单数量
     */
    @GetMapping("/getOrderStateCount")
    public Result<?> getOrderStateCount(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());
        EntityWrapper<JazUserOrderDO> wrapper = new EntityWrapper<JazUserOrderDO>();
        //查询待开始订单数量
        wrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
        wrapper.andNew().eq("status",0);
        int dks = jazUserOrderService.selectCount(wrapper);

        wrapper = new EntityWrapper<JazUserOrderDO>();
        //查询进行中订单数量
        wrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
        wrapper.andNew().eq("status",1);
        int jxz = jazUserOrderService.selectCount(wrapper);

        wrapper = new EntityWrapper<JazUserOrderDO>();
        //查询已完成订单数量
        wrapper.eq("initiate_id",userDO.getId()).or().eq("signing_id",userDO.getId());
        wrapper.andNew().eq("status",2);
        int ywc = jazUserOrderService.selectCount(wrapper);

        Map map =new HashMap();
        map.put("dksCount",dks);
        map.put("jxzCount",jxz);
        map.put("ywcCount",ywc);
        return Result.ok(map);
    }




}
